#include "ServerSocket.h"


ServerSocket::ServerSocket(SOCKET sockfd): Socket(sockfd)
{
}

ServerSocket::ServerSocket()
{
}

ServerSocket::~ServerSocket()
{
}


void ServerSocket::Listen(unsigned short port, unsigned int backlog)
{
	struct sockaddr_in listenaddr;

	listenaddr.sin_family = AF_INET;
    listenaddr.sin_port = htons(port);
    listenaddr.sin_addr.s_addr = INADDR_ANY;
    memset(listenaddr.sin_zero, 0, sizeof(listenaddr.sin_zero));

    if (bind(GetSocket(), (struct sockaddr *)&listenaddr, sizeof(listenaddr)) == -1) 
	{
		throw SocketException();
    }

    if (listen(GetSocket(), backlog) == -1) 
	{
		throw SocketException();
    }
}

Socket ServerSocket::Accept()
{
	struct sockaddr_in clientaddr;
	int clientaddrlen;
	SOCKET clientsockfd;

    clientaddrlen = sizeof(clientaddr);
	clientsockfd = accept(GetSocket(), (struct sockaddr *)&clientaddr, &clientaddrlen);

	if (clientsockfd == -1)
	{ 
		throw SocketException();
	} 

	return Socket(clientsockfd);
}

